package com.example.demo.tool;

/**
 * TODO
 *
 * @author mazh47622
 * @date2024/2/21
 * @modify -----------------------------------------------------------------------------------------------------
 * |修改单号|修改人员|修改日期|评审人员|修改说明
 * -----------------------------------------------------------------------------------------------------
 * |      |       |      |       |
 * -----------------------------------------------------------------------------------------------------
 */
public class IdCardUtils {
    public static boolean isValidIdCard(String idCard) {
        // 18位身份证号码的格式为6位地址码 + 8位生日 + 3位顺序码 + 1位校验码
        String regex = "^\\d{17}[\\dX]$";
        if (!idCard.matches(regex)) {
            return false;
        }

        // 权重因子
        int[] weights = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
        // 校验数组
        char[] codes = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
        // 校验码计算
        int sum = 0;
        for (int i = 0; i < 17; i++) {
            sum += (idCard.charAt(i) - '0') * weights[i];
        }
        int index = sum % 11;
        if (idCard.charAt(17) != codes[index]) {
            return false;
        }

        return true;

    }
}
